package com.woniuxy.joylifemarket.controller;

import com.woniuxy.common.entity.MarketMessage;
import com.woniuxy.common.entity.MarketTalk;
import com.woniuxy.joylifemarket.service.MarketMessageService;
import com.woniuxy.joylifemarket.service.MarketTalkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class TalkController {
    @Autowired
    MarketTalkService marketTalkService;
    @Autowired
    MarketMessageService marketMessageService;

    //加载全部聊天内容
    @RequestMapping("/inittalks")
    public Object userAddress(String loginuserid,String commodityid,String userid) {
            Map<String, Object> result = new HashMap<>();
            try {
                List<MarketTalk> allTalksByInfo = marketTalkService.findAllTalksByInfo(loginuserid, commodityid, userid);
                result.put("code", 200);
                result.put("msg", "查询成功");
                result.put("data", allTalksByInfo);
//                System.out.println("allTalksByInfo"+allTalksByInfo);
                return result;
            } catch (Exception e) {
                result.put("code", 500);
                result.put("msg", "查询失败");
                e.printStackTrace();
                return result;
            }
        }

    //发送聊天
    @RequestMapping("/submittalk")
    public Object submitTalk(String loginuserid,String commodityid,String userid,String talk) {
        Map<String, Object> result = new HashMap<>();
        try {
            int insert = marketTalkService.insertTalkByInfo(loginuserid, commodityid, userid, talk);
            if (insert!=0) {
                //发送消息时查询有没有这个消息
                MarketMessage searchMarketMessage = marketMessageService.selectMessageByInfo(loginuserid, commodityid, userid);
                if (searchMarketMessage==null) {
                    //没有消息先创建消息，让它能显示在列表
                    int i = marketMessageService.insertMessageByInfo(loginuserid, commodityid, userid);
                    MarketMessage marketMessage = marketMessageService.selectMessageByInfo(loginuserid, commodityid, userid);
                }else{
                    //更新消息最后接收时间
                    int update = marketMessageService.updateDate(searchMarketMessage.getId(), new Date());
                }
                result.put("code", 200);
                result.put("msg", "查询成功");
                return result;
            }
            result.put("code", 500);
            result.put("msg", "查询失败");
            return result;
        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "查询失败");
            e.printStackTrace();
            return result;
        }
    }
}
